//
//  HXDEmoticonCell.swift
//  weibo
//
//  Created by huxuedong on 15/12/15.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

class HXDEmoticonCell: UICollectionViewCell {
    
    private lazy var emoticonButtons: [HXDEmoticonButton] = [HXDEmoticonButton]()
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        return button
    }()
    private lazy var usedLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), textSize: 11)
        label.text = "最近使用的表情"
        return label
    }()
    //根据Xib创建popView
    private lazy var popView: HXDEmoticonPopView = HXDEmoticonPopView.popView()

    var indexPath: NSIndexPath? {
        didSet {
            //不是第0组时，隐藏最近使用的表情label
            usedLabel.hidden = indexPath?.section != 0
        }
    }
    
    var emoticons: [HXDEmoticon]? {
        didSet {
            //隐藏所有按钮，因为cell会重用，没有表情图片数据时不显示按钮
            for value in emoticonButtons {
                value.hidden = true
            }
            //遍历表情数据
            for (i, emoticon) in emoticons!.enumerate() {
                let button = emoticonButtons[i]
                button.hidden = false
                //设置表情
                button.emoticon = emoticon
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addEmoticonButton()
        contentView.addSubview(deleteButton)
        contentView.addSubview(usedLabel)
        usedLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-10)
        }
        //创建长按手势
        let gesture = UILongPressGestureRecognizer(target: self, action: "longPressGesture:")
        //添加手势
        contentView.addGestureRecognizer(gesture)
    }
    
    private func addEmoticonButton() {
        //遍历当前页的表情按钮
        for _ in 0..<kEmoticonNumOfPage {
            let button = HXDEmoticonButton()
            //设置表情按钮图片的大小
            button.titleLabel?.font = UIFont.systemFontOfSize(33)
            button.addTarget(self, action: "emoticonButtonClick:", forControlEvents: .TouchUpInside)
            contentView.addSubview(button)
            emoticonButtons.append(button)
        }
    }
    
    @objc private func emoticonButtonClick(button: HXDEmoticonButton) {
        NSNotificationCenter.defaultCenter().postNotificationName("emoticonButtonClick", object: nil, userInfo: ["emoticon":button.emoticon!])
        //将点击的表情按钮保存到最近表情中
        HXDEmoticonTools.sharedInstance.saveRecentEmoticon(button.emoticon!)
        let popView = HXDEmoticonPopView.popView()
        button.showPopView(popView)
        //延迟0.1秒消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            popView.removeFromSuperview()
        })
    }
    
    @objc private func longPressGesture(gesture: UILongPressGestureRecognizer) {
        
        func getButtonWithLocation(location: CGPoint) -> HXDEmoticonButton? {
            for button in emoticonButtons {
                if CGRectContainsPoint(button.frame, location) {
                    return button
                }
            }
            return nil
        }
        
        switch gesture.state {
        case .Began, .Changed:
            //获取当前触屏点的坐标
            let location = gesture.locationInView(contentView)
            if let targetButton = getButtonWithLocation(location) {
                popView.hidden = false
                targetButton.showPopView(popView)
            }
        case .Ended:
            let location = gesture.locationInView(contentView)
            if let targetButton = getButtonWithLocation(location) {
                emoticonButtonClick(targetButton)
            }
            popView.hidden = true
        default:
            popView.hidden = true
        }
        
    }
    
    @objc private func deleteButtonClick() {
      NSNotificationCenter.defaultCenter().postNotificationName("deleteEmoticon", object: nil)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let leftMargin: CGFloat = 5
        let bottomMargin: CGFloat = 25
        let emoticonButtonW = (width - leftMargin * 2) / CGFloat(kColumnsOfPage)
        let emoticonButtonH = (height - 25) / CGFloat(kRowsOfPage)
        //遍历表情按钮数组
        for (i, value) in emoticonButtons.enumerate() {
            //设置表情按钮的size、x、y
            value.size = CGSize(width: emoticonButtonW, height: emoticonButtonH)
            let columnIndex = i % kColumnsOfPage
            let rowIndex = i / kColumnsOfPage
            value.x = CGFloat(columnIndex) * emoticonButtonW + leftMargin
            value.y = CGFloat(rowIndex) * emoticonButtonH
        }
        //删除按钮的size、x、y
        deleteButton.size = CGSize(width: emoticonButtonW, height: emoticonButtonH)
        deleteButton.x = width - emoticonButtonW - leftMargin
        deleteButton.y = height - emoticonButtonH - bottomMargin
    }
    
}
